package org.ourgrid.common.statistics.control;

import org.ourgrid.common.interfaces.to.GridProcessAccounting;
import org.ourgrid.common.statistics.beans.peer.Job;
import org.ourgrid.common.statistics.util.hibernate.HibernateUtil;
import org.ourgrid.peer.dao.statistics.JobDAO;
import org.ourgrid.peer.to.Request;

import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;

public class JobControl extends EntityControl {
	
	private static JobControl instance = null;
	
	public static JobControl getInstance() {
		if (instance == null) {
			instance = new JobControl();
		}
		return instance;
	}
	
	protected JobControl() {}
	
	public void addRequest(Request request, ServiceManager serviceManager) {
		logger.enter();
		
		HibernateUtil.beginTransaction();

		try {
			serviceManager.getDAO(JobDAO.class).addRequest(request);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		logger.leave();
	}
	
	public void addProcessAccounting(GridProcessAccounting replicaAccounting, ServiceManager serviceManager) {

		logger.enter();
		
		HibernateUtil.beginTransaction();
		
		try {
			serviceManager.getDAO(JobDAO.class).addProcessAccounting(replicaAccounting);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		logger.leave();
	}	
	
	public void finishRequest(Request request, boolean clientFailure, ServiceManager serviceManager) {
		
		logger.enter();
		
		HibernateUtil.beginTransaction();
		
		try {
			serviceManager.getDAO(JobDAO.class).finishRequest(request, clientFailure);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		logger.leave();
	}

	public Job findByRequestId(long requestId, ServiceManager serviceManager) {
		logger.enter();
		
		HibernateUtil.beginTransaction();
		
		Job job = null;
		try {
			job = serviceManager.getDAO(JobDAO.class).findByRequestId(requestId);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		logger.leave();
		
		return job;
	}
	
	

}
